<template>
  <div class="BP-manage-container">
    <ListTab v-if="!showMobilePage" show-header />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="min-fill-page BP-manage-list">
      <div v-if="!showMobilePage" class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
        <createBtn v-if="hasRouteAuth('crm:BPManage:create')" @click.native="BPDialogShow(false)"/>
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list.items.length"
            :data="list.items"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @sort-change="sortMethod">
            <u-table-column :min-width="handleTdWidth(120, 200)" align="left" label="BP类型" sortable="custom" prop="name">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.name" />
              </template>
            </u-table-column>
            <u-table-column :min-width="handleTdWidth(120, 200)" align="left" label="BP人员" sortable="custom" prop="userStr">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.userStr" />
              </template>
            </u-table-column>
            <u-table-column :min-width="handleTdWidth(120, 200)" align="left" label="负责部门">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.deptStr" />
              </template>
            </u-table-column>
            <u-table-column :min-width="handleTdWidth(80, 100)" align="left" label="更新人" sortable="custom" prop="updator">
              <template slot-scope="scope">
                <CheckUserInfo :user-id="scope.row.updatorId" :label="scope.row.updator" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="更新时间" min-width="160" sortable="custom" prop="updateTime">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.updateTime, 'YYYY/MM/DD HH:mm:ss')" />
              </template>
            </u-table-column>
            <u-table-column :min-width="handleTdWidth(80, 100)" align="left" label="创建人" sortable="custom" prop="creator">
              <template slot-scope="scope">
                <CheckUserInfo :user-id="scope.row.creatorId" :label="scope.row.creator" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160" sortable="custom" prop="createTime">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime, 'YYYY/MM/DD HH:mm')" />
              </template>
            </u-table-column>
            <u-table-column
              v-if="hasRouteAuth('crm:BPManage:create')"
              :width="operateWidth"
              align="left"
              label="操作"
              fixed="right">
              <template slot-scope="scope">
                <div v-if="!showMobilePage" class="operation-btn-group">
                  <el-button type="text" @click.stop="handleBPEdit(scope.row)">编辑</el-button>
                  <div class="btn-divider" />
                  <el-button class="del-btn" type="text" @click.stop="handleBpDel(scope.row.id)">删除</el-button>
                </div>
                <tableOperateBtn v-else>
                  <el-dropdown-item style="width:90px;text-align: center" @click.native="handleBPEdit(scope.row)">
                    <div style="font-size: 14px">编辑</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="width:90px;text-align: center" @click.native="handleBpDel(scope.row.id)">
                    <div style="font-size: 14px">删除</div>
                  </el-dropdown-item>
                </tableOperateBtn>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" slot="empty" empty-text="暂无数据" mode="table" style="padding-bottom: 0;" />
          <el-row v-if="showMobilePage" type="flex" justify="left">
            <el-pagination
              v-show="list.total > 0"
              :current-page="page"
              :page-size="perPage"
              :total="list.total"
              :small="true"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="pageLayout"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </div>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-mobile-icon
              show-search-btn
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <createBtn
              v-if="hasRouteAuth('crm:BPManage:create')"
              mobile-table
              style="width: 100%"
              @click.native="BPDialogShow(false)"/>
          </template>
          <template v-else>
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
    <BPStoreDialog
      ref="BPStoreDialogRef"
      :dept-tree-list="deptTreeList"
      :loading="BPStoreLoading"
      @handleBPEdit="handleBPStore($event, true)"
      @handleBPCreate="handleBPStore($event, false)"
    />
  </div>
</template>
<script>
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
// 组件
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import ListTab from '@/components/ListTab';
import BPStoreDialog from './BPStoreDialog';
// api
import { getBPList, BPDelete, BPCreate, BPEdit } from '@/api/BPManage';
import { getDepartmentAll } from '@/api/config';
import { format } from '@/filters/date';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { showModal } from '@/utils/message';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';

export default {
  name: 'BPManage',
  components: {
    EmptyPlaceholder,
    createBtn,
    BPStoreDialog,
    ListTab
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      sortName: '',
      sortType: '',
      page: 1,
      perPage: 20,
      paramsObj: {},
      listLoading: false,
      BPStoreLoading: false,
      deptTreeList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 148 : 188;
    },
    rangeKeyArr() {
      return [
        { attr: 'createTime', start: 'createTimeStart', end: 'createTimeEnd', type: 'time' },
        { attr: 'updateTime', start: 'updateTimeStart', end: 'updateTimeEnd', type: 'time' }
      ];
    },
    arrayKeyArr() {
      return ['depts'];
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'name', name: 'BP类型', type: 'input' },
        { keyword: 'users', name: 'BP人员', type: 'input' },
        { keyword: 'creator', name: '创建人', type: 'input' },
        { keyword: 'updator', name: '更新人', type: 'input' },
        // 下拉
        { keyword: 'depts', name: '负责部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        // 日期
        { keyword: 'createTime', name: '创建时间', timeType: 'daterange', type: 'rangeDate', startPlaceholder: '开始时间', endPlaceholder: '结束时间' },
        { keyword: 'updateTime', name: '更新时间', timeType: 'daterange', type: 'rangeDate', startPlaceholder: '开始时间', endPlaceholder: '结束时间' }
      ];
      return arr;
    }
  },
  created() {
    this.queryDeptTreeList();
    this.fetchData(true);
  },
  methods: {
    hasRouteAuth,
    format,
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && [{ id: -1, name: '所有部门' }, ...res.data]) || [];
      });
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    fetchData(reset = false) {
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      getBPList(params).then(res => {
        if (res.code === 200) {
          this.list = res.data;
        }
      }).catch(err => console.log(err)).finally(() => {
        this.listLoading = false;
        this.list.isInit = false;
      });
    },
    formatParams() {
      const params = _.cloneDeep(this.paramsObj);
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      return params;
    },
    BPDialogShow(isEdit = false) {
      this.$refs['BPStoreDialogRef'].dialogVisible = true;
      this.$refs['BPStoreDialogRef'].isEdit = isEdit;
    },
    handleBPEdit(BPData = {}) {
      this.BPDialogShow(true);
      this.$nextTick(() => {
        this.$refs['BPStoreDialogRef'].initBPDialog(BPData);
      });
    },
    // BP添加/编辑
    handleBPStore(data, isEdit) {
      this.BPStoreLoading = true;
      const apiFun = isEdit ? BPEdit : BPCreate;
      apiFun(data).then(_ => {
        this.$message.success('BP设置成功');
        this.BPStoreLoading = false;
        this.$refs['BPStoreDialogRef'].handleDialogClose();
        this.fetchData();
      }).catch(err => {
        this.BPStoreLoading = false;
        console.log(err);
      });
    },
    handleBpDel(id) {
      showModal('是否确定删除?').then(() => {
        BPDelete(id).then(_ => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.fetchData();
        }).catch(err => { console.log(err); });
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = '';
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    }
  }
};
</script>
<style lang="scss" scoped>
.BP-manage-container{
  .BP-manage-list{
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 24px 55px 24px;
  }
  .filter {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    position: relative;
  }
  .operation-btn-group {
    display: flex;
    align-items: center;
    white-space: nowrap;
    .btn-divider {
      height: 12px;
      width: 1px;
      background-color: #ddd;
      margin: 0 8px;
    }
    .del-btn {
      color: red;
    }
    .el-button {
      font-size: 14px;
    }
  }
}
</style>
